from flask import g, render_template, current_app, abort, jsonify, request

from info.utils.common import user_getter
from info import constants, db
from info.models import News, User, Comment
from info.utils.response_code import RET
from . import news_blue


@news_blue.route('/news_comment', methods = ["POST"])
@user_getter
def news_comment():
    # 获取用户
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 获取参数
    news_id = request.json.get("news_id")
    comment_str = request.json.get("comment")
    parent_id = request.json.get("parent_id") # 可以为空
    if not all([news_id, comment_str]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 校验新闻和用户登录状态
    try:
        user = User.query.get(user.id)
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="新闻无数据")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="用户无数据")

    # 创建评论模型
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    print(news_id)
    comment.content = comment_str
    if parent_id:
        comment.parent_id = parent_id

    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    return jsonify(errno=RET.OK, errmsg="成功", data=comment.to_dict())


@news_blue.route('/news_collect', methods=["POST"])
@user_getter
def news_collect():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 判断参数完整性,以及action是否正确
    if not all([news_id, action]) or action not in ["collect", 'cancel_collect']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        user = User.query.get(user.id)
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    if not user:
        return jsonify(errno=RET.NODATA, errmsg="找不到该用户")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="找不到该新闻")

    # 如果数据库中用户已收藏该新闻 且 动作是取消收藏
    if news in user.collection_news and action == "cancel_collect":
        user.collection_news.remove(news)
    # 如果数据库中用户未收藏, 且动作是收藏
    elif news not in user.collection_news and action == "collect":
        user.collection_news.append(news)

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="保存失败")

    return jsonify(errno=RET.OK, errmsg="成功")


@news_blue.route('/<news_id>')
@user_getter
def index(news_id):
    """
    文章详情页
    返回json数据,字典data包含
    is_collected 用户是否收藏
    news: 新闻的详情字典
    click_news_list: 热点新闻列表
    user: 用户的信息字典()
    """

    # 获取用户信息
    user = g.user

    # 查询新闻详情
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger(e)
        abort(404)
    # 如果可以查找到新闻,则点击数加1,否则返回404错误
    if news:
        news.clicks += 1
    else:
        abort(404)

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger(e)

    # 是否收藏
    is_collected = False
    if user and news in user.collection_news:
        is_collected = True

    # 查询新闻排行
    news_models = None
    try:
        news_models = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    click_news_list = []
    for top_news in news_models if news_models else []:
        click_news_list.append(top_news.to_basic_dict())

    # 查询用户用户评论
    comments = []
    try:
        comments = Comment.query.filter_by(news_id=news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库错误")
    comments_list = []
    for comment in comments:
        comments_list.append(comment.to_dict())

    data = {
        "user": user.to_index_dict() if user else None,
        "news": news.to_dict(),
        "click_news_list": click_news_list,
        "is_collected": is_collected,
        "comments":comments_list
    }
    return render_template("news/detail.html", data=data)
